<?php
namespace UserApi\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class CoursesApiController extends AbstractRestfulController
{
    public function getList()
    {			
		header('Access-Control-Allow-Origin: *');
		$courseTable=$this->getServiceLocator()->get('Models\Model\CoursesFactory');
		$courseList = $courseTable->getCourselist();
		if(($courseList->count())!=0){
			$data = array();$i=0;
			foreach($courseList as $courses){
				$cid=$courses->course_id;
				$data[$i]['sno']=$i+1;
				$data[$i]['course_name']= $courses->course_name;
				$data[$i]['action']='<a href="javascript:void(0)" onclick = "editCourseFunction('.$cid.')">Edit</a> &nbsp;/&nbsp;<a href="javascript:void(0);" onClick="deleteCourse('.$cid.')">Delete</a>';
				$i++;
			}
			$data['aaData'] = $data;
			echo json_encode($data['aaData']); exit;
		}else{
			return new JsonModel(array(
				'output' 	=> 'no data',
				'value'		=>	0,
			));
		}	
    }
    public function get($course_id)
    {		
		header('Access-Control-Allow-Origin: *');		
		$courseTable=$this->getServiceLocator()->get('Models\Model\CoursesFactory');
		if($course_id==0){
			$editCourse = $courseTable->getCourselist()->toArray();
		}else{
			$editCourse= $courseTable->editCourse($course_id)->toArray();
		}
		if(count($editCourse)!=0){
			return new JsonModel(array(
				'editCourse'  => json_encode($editCourse),
				'value' 	  => 1,
			));
		}else{
			return new JsonModel(array(
				'output'  => 'no data',
				'value'   => 0,
			));
		}
    }
    public function create($data)
    {
		header('Access-Control-Allow-Origin: *');	
		$courseTable=$this->getServiceLocator()->get('Models\Model\CoursesFactory');
		if($data['hid_course_id']==""){
			$saveCourse = $courseTable->saveCourse($data);
		}else{
			$saveCourse =$courseTable->update_course($data);
		}
		return new JsonModel(array(
			'output' 	=> 	'success',
			'courseId'	=>	$saveCourse,
			'value' 	=> 	1,
		));	
    }
    public function update($course_id, $data)
    {
		header('Access-Control-Allow-Origin: *');	
		$courseTable=$this->getServiceLocator()->get('Models\Model\CoursesFactory');
		$updateCourse = $courseTable->updateCourse($course_id,$data);
			return new JsonModel(array(
				'output'	 => 'success',
				'courseId' 	 => $updateCourse,
				'value'		 => 1,
			));
    }
    public function delete($courseid)
    {
       $courseTable=$this->getServiceLocator()->get('Models\Model\CoursesFactory');
		$deleteCourse = $courseTable->deleteCourse($courseid);
			if($deleteCourse!=0){
				return new JsonModel(array(
					'status'		=>	'success',
					'value'			=>	1,
				));	
			}else{
				return new JsonModel(array(
					'status'	=>	'fail',
					'value'		=>   0,
				));			
			}
    }
}